import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

import 'detail.dart';

Dio dio = Dio();

class MovieList extends StatefulWidget {
  // 传递数据到新页面
  const MovieList({super.key, required this.title});

  final String title;

  @override
  State<StatefulWidget> createState() {
    return _MovieListState();
  }
}

// 有状态组件必须结合一个状态管理类来进行实现 'with AutomaticKeepAliveClientMixin' => 实现记住当前页面的状态
class _MovieListState extends State<MovieList> with AutomaticKeepAliveClientMixin{
  // 默认显示第一页数据
  var page = 1;
  // 每页显示的数据条数
  var pageSize = 10;
  // 电影列表数据
  var movieList = [];
  // 总条数
  var total = 0;

  // 初始化状态
  @override
  void initState() {
    super.initState();
    // 获取电影列表数据
    getMovieList();
  }

  // 渲染当前MovieList组件的UI结构
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: movieList.length,
      itemBuilder: (context, index) {
        return GestureDetector(
          onTap: () {
            Navigator.push(context, MaterialPageRoute(builder: (context) {
              return MovieDetail(id: movieList[index]["id"], title: movieList[index]["title"]);
            }));
          },
          child: Container(
            height: 200,
            decoration: const BoxDecoration(
              border: Border(
                top: BorderSide(width: 1, color: Colors.black12),
              ),
            ),
            child: Row(
              children: [
                Image.network(
                  movieList[index]["images"]["small"],
                  width: 130,
                  height: 180,
                  fit: BoxFit.cover,
                ),
                Container(
                  padding: const EdgeInsets.all(10),
                  height: 200,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      Text("电影名称：${movieList[index]["title"]}"),
                      Text("上映年份：${movieList[index]["year"]}"),
                      Text("电影类型：${movieList[index]["genres"].join(",")}"),
                      Text("豆瓣评分：${movieList[index]["rating"]["average"]}"),
                      Text("主要演员：${movieList[index]["title"]}"),
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  // 获取电影列表数据
  getMovieList() async {
    // 计算当前页的开始位置
    var start = (page - 1) * pageSize;
    var response = await dio.get("http://www.liulongbin.top:3005/api/v2/movie/${widget.title}?start=$start&count=$pageSize");
    var result = response.data;
    print(result);
    setState(() { // 数据赋值必须放到setState方法中
      movieList = result["subjects"];
      total = result["total"];
    });
  }

  // 实现记住当前页面的状态
  @override
  bool get wantKeepAlive => true;
}